<?php

namespace Rjyst\RjCategoryModule\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\DB;

class UninstallCommand extends Command
{
    protected $signature = 'rj-category-module:uninstall {--force : Force uninstall without confirmation}';
    protected $description = 'Uninstall RjYst Category Module package';

    public function handle()
    {
        $this->info('🗑️  开始卸载 RjYst Category Module 扩展包...');

        if (!$this->option('force')) {
            if (!$this->confirm('确定要卸载 RjYst Category Module 扩展包吗？这将删除所有相关文件和数据表！')) {
                $this->info('卸载已取消');
                return;
            }
        }

        // 1. 删除数据表
        $this->dropTables();

        // 2. 删除模型文件
        $this->deleteModels();

        // 3. 删除管理后台文件
        $this->deleteAdminFiles();

        // 4. 删除 Seeders
        $this->deleteSeeders();

        // 5. 删除迁移文件
        $this->deleteMigrations();

        // 6. 移除路由
        $this->removeRoute();

        // 7. 删除菜单
        $this->deleteMenu();

        // 8. 恢复 Category 模型
        $this->restoreCategoryModel();
        // 9. 删除配置文件
        $this->deleteConfig();

        $this->info('🎉 RjYst Category Module 扩展包卸载完成！');
    }

    protected function dropTables()
    {
        $this->info('删除数据表...');

        if (Schema::hasTable('category_modules')) {
            Schema::dropIfExists('category_modules');
            $this->info("✅ 删除表 category_modules");
        } else {
            $this->line("⚠️  表 category_modules 不存在");
        }
    }
    protected function restoreCategoryModel()
    {
        $this->info('恢复 Category 模型...');

        $categoryModelPath = app_path('Models/Category/Category.php');

        if (!File::exists($categoryModelPath)) {
            $this->line('⚠️  Category 模型不存在');
            return;
        }

        $content = File::get($categoryModelPath);

        // 移除 CategoryModule 相关的 use 语句
        $content = str_replace("use App\Models\Category\CategoryModule;\n", '', $content);
        $content = str_replace("\nuse App\Models\Category\CategoryModule;", '', $content);

        // 移除 category_module 关联方法
        $categoryModuleMethodPattern = '/\n\s*public function category_module\(\): Relations\\HasMany\s*\{[^}]*\}\s*/';
        $content = preg_replace($categoryModuleMethodPattern, '', $content);

        // 清理多余的空行
        $content = preg_replace("/\n{3,}/", "\n\n", $content);

        File::put($categoryModelPath, $content);
        $this->info('✅ Category 模型恢复完成');
    }

    protected function deleteModels()
    {
        $this->info('删除模型文件...');

        $categoryModuleModel = app_path('Models/Category/CategoryModule.php');

        if (File::exists($categoryModuleModel)) {
            File::delete($categoryModuleModel);
            $this->info("✅ 删除模型: CategoryModule.php");
        } else {
            $this->line("⚠️  模型不存在: CategoryModule.php");
        }

        // 检查 Category 目录是否为空，如果为空则删除
        $categoryDir = app_path('Models/Category');
        if (File::isDirectory($categoryDir) && count(File::files($categoryDir)) === 0) {
            File::deleteDirectory($categoryDir);
            $this->info('✅ 删除空目录: Models/Category');
        }
    }

    protected function deleteAdminFiles()
    {
        $this->info('删除管理后台文件...');

        $adminFiles = [
            app_path('Admin/Controllers/Category/CategoryModuleController.php'),
            app_path('Admin/Repositories/Category/CategoryModule.php'),
        ];

        foreach ($adminFiles as $filePath) {
            if (File::exists($filePath)) {
                File::delete($filePath);
                $this->info("✅ 删除文件: " . str_replace(app_path('Admin/'), '', $filePath));
            } else {
                $this->line("⚠️  文件不存在: " . str_replace(app_path('Admin/'), '', $filePath));
            }
        }

        // 检查并删除空目录
        $directories = [
            app_path('Admin/Controllers/Category'),
            app_path('Admin/Repositories/Category'),
        ];

        foreach ($directories as $dir) {
            if (File::isDirectory($dir) && count(File::allFiles($dir)) === 0) {
                File::deleteDirectory($dir);
                $this->info('✅ 删除空目录: ' . str_replace(app_path('Admin/'), 'Admin/', $dir));
            }
        }
    }

    protected function deleteSeeders()
    {
        $this->info('删除 Seeder 文件...');

        $seeders = [
            database_path('seeders/CategoryModuleSeeder.php'),
            database_path('seeders/CategoryModuleMenuSeeder.php'),
        ];

        foreach ($seeders as $seederPath) {
            if (File::exists($seederPath)) {
                File::delete($seederPath);
                $this->info("✅ 删除 Seeder: " . basename($seederPath));
            } else {
                $this->line("⚠️  Seeder 不存在: " . basename($seederPath));
            }
        }
    }

    protected function deleteMigrations()
    {
        $this->info('删除迁移文件...');

        $migrationPath = database_path('migrations/2025_09_09_011903_create_category_modules_table.php');

        if (File::exists($migrationPath)) {
            File::delete($migrationPath);
            $this->info("✅ 删除迁移文件: 2025_09_09_011903_create_category_modules_table.php");
        } else {
            $this->line("⚠️  迁移文件不存在");
        }

        // 删除迁移记录
        try {
            DB::table('migrations')
                ->where('migration', '2025_09_09_011903_create_category_modules_table')
                ->delete();
            $this->info('✅ 删除迁移记录');
        } catch (\Exception $e) {
            $this->warn('⚠️  删除迁移记录失败: ' . $e->getMessage());
        }
    }

    protected function removeRoute()
    {
        $this->info('移除路由...');

        $routeFile = app_path('Admin/routes.php');

        if (!File::exists($routeFile)) {
            $this->warn('⚠️  Admin routes.php 文件不存在');
            return;
        }

        $content = File::get($routeFile);

        // 查找并移除包含 category_module 的路由行
        $lines = explode("\n", $content);
        $filteredLines = array_filter($lines, function($line) {
            return strpos($line, 'category_module') === false;
        });

        if (count($filteredLines) < count($lines)) {
            $newContent = implode("\n", $filteredLines);
            // 清理多余的空行
            $newContent = preg_replace("/\n{3,}/", "\n\n", $newContent);

            File::put($routeFile, $newContent);
            $this->info('✅ 移除路由');
        } else {
            $this->line('⚠️  路由不存在');
        }
    }

    protected function deleteMenu()
    {
        $this->info('删除菜单...');

        try {
            $deleted = DB::table('admin_menu')
                ->where('title', '书籍模块')
                ->delete();

            if ($deleted > 0) {
                $this->info('✅ 删除菜单');
            } else {
                $this->line('⚠️  菜单不存在');
            }

        } catch (\Exception $e) {
            $this->warn('⚠️  删除菜单失败: ' . $e->getMessage());
        }
    }

    protected function deleteConfig()
    {
        $this->info('删除配置文件...');

        $configFile = config_path('rj-category-module.php');

        if (File::exists($configFile)) {
            File::delete($configFile);
            $this->info("✅ 删除配置文件");
        } else {
            $this->line("⚠️  配置文件不存在");
        }
    }
}
